import os, shutil
from pathlib import Path


def copy_all_file_in_dir(dir: str, tar: str):
    if dir[-1] != "/":
        dir += "/"
    shutil.copytree(dir, tar, dirs_exist_ok=True)
    for f in os.listdir(dir):
        #print("file in " + listed_dirs[i] + " " + f)
        shutil.copy(dir + f, tar + f)

       
def copy_files(listed_dirs, tar_dirs):
     for i in range(len(listed_dirs)):
        curpath = Path(listed_dirs[i])
        if curpath.is_file():
            shutil.copy(listed_dirs[i], tar_dirs[i])
            #print("copy: " + listed_dirs[i] + " " + tar_dirs[i])
        elif curpath.is_dir():
            #if listed_dirs[i][-1] != "/":
            #    listed_dirs[i] += "/"
            #shutil.copytree(listed_dirs[i], tar_dirs[i], dirs_exist_ok=True)
            #for f in os.listdir(listed_dirs[i]):
             #   #print("file in " + listed_dirs[i] + " " + f)
             #   shutil.copy(listed_dirs[i] + f, tar_dirs[i] + f)
            copy_all_file_in_dir(listed_dirs[i], tar_dirs[i])
        else:
            print("unknown: " + curpath.__str__())
            
def os_mkdir(dir):
    mkdir_command = "mkdir -p " + dir
    #print(mkdir_command)
    os.system(mkdir_command)
    
def os_cp_dir_force(src, dst):
    pre_cp_command = "cp -r -f "
    command = pre_cp_command + src + ' ' + dst
    os.system(command)
            
def create_dir_if_possible(src, dst):
    is_dir = Path(src).is_dir()
    if is_dir:
        # make dir first
        os_mkdir(dst) 
        return is_dir

def system_copy_files(listed_dirs, tar_dirs):
    for i in range(len(listed_dirs)):
        is_dir = create_dir_if_possible(listed_dirs[i], tar_dirs[i])
        
        to = ""
        if is_dir:
            for t in tar_dirs[i].split('/')[:-1]:
                to = to + t + '/'
        else:
            to = tar_dirs[i]
            
        os_cp_dir_force(listed_dirs[i], to)
